<?php
declare (strict_types = 1);

namespace app\admin\controller;
use app\admin\middleware\Auth;
use app\model\OrderAftersalesModel;
use app\model\OrdersModel;
use app\model\RedisModel;
use app\model\ShopsModel;
use app\model\UserFbLogModel;
use EasyWeChat\Factory;
use think\App;
use think\facade\Db;

class OrderSaftersales extends Base {

    protected $middleware = [Auth::class];

    public $cacheKey="order:aftersale:id:";

    private $aid;

    private $shopsModel;

    private $orderModel;

    private $req;

    private $shop_id;

    private $shopIds;

    private $orderAftersalesModel;


    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->req = request()->param();

        $this->shop_id = isset($this->req['shop_id']) ? $this->req['shop_id'] : "";

        $this->page = isset($this->req['page']) ? $this->req['page'] : 1;

        $this->limit = isset($this->req['limit']) ? $this->req['limit'] : 20;

        $this->shopsModel = new ShopsModel();

        $this->orderModel = new OrdersModel();

        $this->aid = $this->isLogin();

        if(!$this->aid){
            return $this->noLogin();
        }

        $this->shopIds = $this->shopsModel->getShopIds($this->aid);

        $this->orderAftersalesModel = new OrderAftersalesModel();

    }


    /*
     * 审核通过
     *
     * */

    public function aftersalesIsPass(){

        if(empty($this->req["order_after_sale_id"])){
            return $this->fail("参数错误：order_after_sale_id 不能为空");
        }

        $orderAftersalesInfo = $this->orderAftersalesModel->getInfo($this->req["order_after_sale_id"]);

        if(!$orderAftersalesInfo){
            return $this->fail("售后订单不存在");
        }

        if($orderAftersalesInfo["aftersale_status"] != 1){
            return $this->fail("售后订单状态不合法,不能完成此操作");
        }
        Db::startTrans();
        $orderAftersalesRes = $this->orderAftersalesModel->updateOrderAftersales($this->req["order_after_sale_id"],["aftersale_status" => 2]);

        $updateOrderAftersaleStatusRes = $this->orderModel->updateOrderAftersaleStatus($orderAftersalesInfo["order_id"],-2);

        if($orderAftersalesRes && $updateOrderAftersaleStatusRes){
            Db::commit();
            return $this->succ("");

        }else{
            Db::rollback();
            return $this->fail("申请失败");

        }
    }


    /*
     * 审核拒绝
     *
     * */

    public function aftersalesIsRefuse(){

        if(empty($this->req["order_after_sale_id"])){
            return $this->fail("参数错误：order_after_sale_id 不能为空");
        }

        $orderAftersalesInfo = $this->orderAftersalesModel->getInfo($this->req["order_after_sale_id"]);

        if(!$orderAftersalesInfo){
            return $this->fail("售后订单不存在");
        }

        if($orderAftersalesInfo["aftersale_status"] == 3){
            return $this->fail("售后订单已完成");
        }

        if(!in_array($orderAftersalesInfo["aftersale_status"],[1,2])){
            return $this->fail("售后订单状态不合法,不能完成此操作");
        }

        Db::startTrans();

        $orderAftersalesRes = $this->orderAftersalesModel->updateOrderAftersales($this->req["order_after_sale_id"],["aftersale_status" => -2]);

        $updateOrderAftersaleStatusRes = $this->orderModel->updateOrderAftersaleStatus($orderAftersalesInfo["order_id"],-2);


        if($orderAftersalesRes && $updateOrderAftersaleStatusRes){

            Db::commit();

            return $this->succ("");

        }else{

            Db::rollback();

            return $this->fail("申请失败");

        }
    }



    /*
   * 退款接口
   *
   * */

    public function aftersalesIsEnd(){

        if(empty($this->req["order_after_sale_id"])){
            return $this->fail("参数错误：order_after_sale_id 不能为空");
        }

        $orderAftersalesInfo = $this->orderAftersalesModel->getInfo($this->req["order_after_sale_id"]);

        $p_totalAmout = $this->orderModel->getOrderTotalAmount($orderAftersalesInfo["p_order_id"]);

        if(!$orderAftersalesInfo){
            return $this->fail("售后订单不存在");
        }

        if($orderAftersalesInfo["aftersale_status"] == 3){
            return $this->fail("售后订单已完成");
        }

        if($orderAftersalesInfo["aftersale_status"] !=2){
            return $this->fail("售后订单状态不合法，订单必须处在审核完成状态才可进行此操作");
        }

        $wxPayRes = $this->wxRefund($orderAftersalesInfo["p_order_id"],$orderAftersalesInfo["order_after_sale_id"],$p_totalAmout,$orderAftersalesInfo["user_refund_amount"],$orderAftersalesInfo["aftersale_reason"]);

        if(!$wxPayRes['res']){
           return $this->fail("退款失败:".$wxPayRes["msg"]);
        }

        $wxReturnInfo = is_array($wxPayRes["data"]) ? json_encode($wxPayRes["data"],256) : "";

        Db::startTrans();
        //更新售后订单状态&和微信退款返回接口落库
        $orderAftersalesRes = $this->orderAftersalesModel->updateOrderAftersales($this->req["order_after_sale_id"],["aftersale_status" => 3,"wx_return_info"=>$wxReturnInfo]);

        //更新订单状态
        $updateOrderStatusRes = $this->orderModel->updateOrderStatus($orderAftersalesInfo["order_id"],-1);
        //更新订单售后状态
        $updateOrderAftersaleStatusRes = $this->orderModel->updateOrderAftersaleStatus($orderAftersalesInfo["order_id"],3);

        //更新福贝记录
        $fbRes =(new UserFbLogModel())->where("order_after_sale_id","=",$this->req["order_after_sale_id"])->update(["fb_status"=>1]);


        if($orderAftersalesRes && $updateOrderStatusRes && $updateOrderAftersaleStatusRes && $fbRes){
            Db::commit();
            return $this->succ("退款成功");
        }else{
            Db::rollback();
            $log=[];
            $log["data"] = $orderAftersalesInfo;
            $log["err"] = "微信退款成功，但订单状态更新失败，请联系开发人员解决，请勿重复退款";
            addWxPayLog("wx_return_db_fail.txt",json_encode($log,256));
            return $this->fail("微信退款成功，但订单状态更新失败，请联系开发人员解决，请勿重复退款");
        }
    }


    /*
* 微信退款
* */
    private function wxRefund($order_id,$order_after_sale_id,$total_amount,$refund_amount,$reason){
        $wxPayConfig = config("wxpay");
        $wxPayConfig['cert_path'] =  app()->getRootPath().$wxPayConfig['cert_path'];
        $wxPayConfig['key_path'] =  app()->getRootPath().$wxPayConfig['key_path'];

        $log =[];
        $log["order_id"] = $order_id;
        $log["order_after_sale_id"] = (String)$order_id.$order_after_sale_id;
        $log["total_amount"] = $total_amount;
        $log["refund_amount"] = $refund_amount;
        $log["reason"] = $reason;
        $response = null;
        try {
            $app = Factory::payment($wxPayConfig);
            // 调用退款接口
            $response = $app->refund->byOutTradeNumber($order_id, (String)$order_id.$order_after_sale_id, (int)$total_amount, (int)$refund_amount, [
                'refund_desc' => $reason,
                // 其他可选参数
            ]);

            $log["response"] = $response;
            // 处理退款结果
            if ($response['return_code'] === 'SUCCESS' && $response['result_code'] === 'SUCCESS') {
                addWxPayLog("wxpay_refund_success.txt",json_encode($log,256));
                // 退款成功
                return ["res"=>true,"data" => $response];
            } else {
                // 退款失败
                addWxPayLog("wxpay_refund_fail.txt",json_encode($log,256));
                return ["res"=>false,"msg"=>"退款失败：" . $response['err_code_des'],"data" => $response];
            }
        }catch (\Exception $e){
            $log["err"] = $e->getMessage();
            addWxPayLog("wxpay_refund_error.txt",json_encode($log,256));
            return ["res"=>false,"msg"=>"退款异常：" .  $e->getMessage(),"data" => $response];
        }

    }

    public function delCache($id)
    {
        $redisModel = new RedisModel();

        return $redisModel->delete($this->cacheKey.$id);
    }


    public function delAllCache()
    {
        $redisModel = new RedisModel();

        return $redisModel->deleteAll($this->cacheKey);
    }

}
